<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class Template
{
	public $folder_admin = FALSE;
	public $layout = 'default';
	public $_data = array();
	
	function __construct($params = array())
    {
        if (count($params) > 0)
        {
            $this->initialize($params);        
        }
    }
    function initialize($params = array())
    {
        if (count($params) > 0)
        {
            foreach ($params as $key => $val)
            {
                if (isset($this->$key))
                {
                    $this->$key = $val;
                }
            }        
        }
    }
    /**
     * Build the entire JSON output, setting the headers for response.
     *
     * @access	public
     * @param	array	$data
     * @return	void
     */
    public function build_json($data = array())
    {
    	ci()->output->set_header('Content-Type: application/json; charset=utf-8');
    	ci()->output->set_output(json_encode((object) $data));
    }
    /**
     * Set data using a chainable metod. Provide two strings or an array of data.
     *
     * @access	public
     * @param	  string
     * @return	mixed
     */
    public function set_data($name, $value = NULL)
    {
    	// Lots of things! Set them all
    	if (is_array($name) OR is_object($name))
    	{
    		foreach ($name as $item => $value)
    		{
    			$this->_data[$item] = $value;
    		}
    	}
    
    	// Just one thing, set that
    	else
    	{
    		$this->_data[$name] = $value;
    	}
    
    	return $this;
    }
    
	public function set($name, $value = NULL)
	{
		if (is_array($name) OR is_object($name))
		{
			foreach ($name as $item => $value)
			{
				$this->$item = $value;
			}
		}
		else
		{
			$this->$name = $value;
		}

		return $this;
	}
	public function load($page, $data = NULL)
	{
		// Set whatever values are given. These will be available to all view files
		is_array($data) OR $data = (array) $data;
		
		$data['page'] = $page;
		
		// Merge in what we already have with the specific data
		$this->_data = array_merge($this->_data, $data);
		// We don't need you any more buddy
		unset($data);

		if ($this->folder_admin == TRUE)
		{
//			设置模板地址为views/admin/
			ci()->load->_ci_view_path .= 'admin/';
		}else{
			ci()->load->_ci_view_path .= 'home/';
		}
//		不设置layout,主要用于ajax调用
		if ($this->layout == FALSE)
		{
			ci()->load->view($this->_data['page'], $this->_data);
		}
		else
		{
			ci()->load->view('layouts/'. $this->layout, $this->_data);
		}
	}
}